package com.indiv.java.web.sx.view.theme;

import java.text.MessageFormat;
import java.util.Locale;

import org.springframework.context.support.ReloadableResourceBundleMessageSource;

public class MessageSourceWithCodeFallback extends
		ReloadableResourceBundleMessageSource {
	@Override
	protected String resolveCodeWithoutArguments(final String code,
			final Locale locale) {

		if (isSpecialLocaleCase(code, locale)) {
			// magic locale for displaying label codes
			return returnCode(code);
		} else {
			return super.resolveCodeWithoutArguments(code, locale);
		}

	}

	@Override
	protected MessageFormat resolveCode(final String code, final Locale locale) {

		if (isSpecialLocaleCase(code, locale)) {
			// magic locale for displaying label codes
			return new MessageFormat(returnCode(code), locale);
		} else {
			return super.resolveCode(code, locale);
		}

	}

	private String returnCode(final String code) {
		return "[" + code + "]";
	}

	private boolean isSpecialLocaleCase(final String code, final Locale locale) {

		if (!locale.getLanguage().equals("dev") || code.startsWith("tiles.")
				|| code.startsWith("conf.") || code.startsWith("javascript.")
				|| code.contains("/") || code.contains(".format")
				|| code.startsWith("webTracking.")) {
			return false;
		}
		return true;
	}
}
